import {logout, getInfo, loginByGet} from '@/api/user'
import {getToken, setToken, removeToken} from '@/utils/auth'
import {resetRouter} from '@/router'
// import de from "element-ui/src/locale/lang/de";

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MENU: (state, menus) => {
    state.menus = menus
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // user login
  login: function ({commit}, userInfo) {
    const {username, password} = userInfo
    return new Promise((resolve, reject) => {
      loginByGet({userName: username.trim(), authCode: password}).then(response => {
        const {token} = response
        commit('SET_TOKEN', token)
        setToken(token) //登录成功后将token存储在cookie之中
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({commit, state}) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const data = response;
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const {name, avatar,menus} = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', "")
        let tmp = {};
        tmp.name = "Admin";
        tmp.roles = "['admin']";
        tmp.avatar = "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif";
        tmp.introduction = "";
        // 保存菜单到vuex
        console.log(menus)
        commit('SET_MENU', menus)
        resolve(tmp)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({commit, state}) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({commit}) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

